<template>
  <div class="search">
    <!-- 顶部导航 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.push('/layout/home')" />
    <!-- 搜索区域 -->
    <div class="sear">
      <van-icon class="myicon" name="search" />
      <input
        class="ipt"
        type="text"
        v-model="key"
        placeholder="请输入搜索关键词"
        @input="search"
      />
      <button class="btn" @click="toResults">搜索</button>
    </div>
    <!-- 历史记录 -->
    <van-cell-group v-if="!key">
      <van-cell class="mytitle" title="历史记录">
        <template #default>
          <van-icon @click="clear" name="cross" />
        </template>
      </van-cell>
      <van-cell
        v-for="(item, index) in historyList"
        :key="index"
        :title="item"
      />
    </van-cell-group>
    <!-- 联想区域 -->
    <van-cell-group v-else>
      <van-cell class="mytitle" title="联想区域" />
      <van-cell v-for="(item, index) in thinkList" :key="index" icon="search">
        <template #title>
          <span @click="toThinkResults(item)" v-html="item"></span>
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getThinkAPI } from "@/api";
export default {
  data() {
    return {
      key: "",
      thinkList: [],
      timer: null,
      historyList: JSON.parse(localStorage.getItem("history")) || [],
    };
  },

  methods: {
    // 清除历史记录
    clear() {
      this.$dialog
        .confirm({
          title: "警告",
          message: "是否删除历史记录",
        })
        .then(() => {
          // on confirm
          this.historyList = [];
          localStorage.removeItem("history");
        })
        .catch(() => {
          // on cancel
        });
    },

    saveToLocal(item) {
      //   排序
      this.historyList.unshift(item);
      //   去重
      this.historyList = [...new Set(this.historyList)];
      //   限长
      if (this.historyList.length > 5) {
        this.historyList.splice(5);
      }
      window.localStorage.setItem("history", JSON.stringify(this.historyList));
    },

    toThinkResults(item) {
      const reg = new RegExp(
        `<span style="color:red">${this.key}</span>`,
        "ig"
      );
      item = item.replace(reg, this.key);
      this.$router.push(`/search/result?key=${item}`);
      this.saveToLocal(item);
    },

    toResults() {
      this.$router.push(`/search/result?key=${this.key}`);
      this.saveToLocal(this.key);
    },
    search() {
      clearTimeout(this.timer);
      this.timer = setTimeout(async () => {
        if (this.key) {
          const res = await getThinkAPI({
            q: this.key,
          });
          console.log(res.data.data.options);
          //   定义正则表达式
          const reg = new RegExp(this.key, "ig");
          this.thinkList = res.data.data.options.map((item) => {
            return item.replace(
              reg,
              `<span style="color:red">${this.key}</span>`
            );
          });
        }
      }, 500);
    },
  },
};
</script>

<style lang="less">
.search {
  font-size: 14px;
  .sear {
    display: flex;
    margin: 10px;
    position: relative;
    .myicon {
      position: absolute;
      top: 10px;
      left: 10px;
    }
    .ipt {
      height: 34px;
      line-height: 34px;
      background-color: #f7f8fa;
      border: none;
      flex: 1;
      border-radius: 17px;
      padding-left: 30px;
    }
    .btn {
      border: none;
      line-height: 34px;
      background: #fff;
    }
  }
  .van-nav-bar__title.van-ellipsis {
    color: #fff;
  }
  i.van-icon.van-icon-arrow-left.van-nav-bar__arrow {
    color: #fff;
  }
  .mytitle {
    font-weight: 700;
  }
}
</style>
